package zhtt.derby.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Service;
import zhtt.derby.entity.User;
import zhtt.derby.mapper.UserMapper;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public Integer count() throws Exception {
        try {
            return userMapper.count();
        } catch (BadSqlGrammarException e) {
            if (e.getSQLException().getSQLState().equals("42X05")) {
                userMapper.create();
            }
        }
        return 0;
    }

    public void create(User user) throws Exception {
        userMapper.insert(user);
    }

    public List<User> query() throws Exception {
        return userMapper.selectAll();
    }

    public List<User> query(int limit, int offset) throws Exception {
        return userMapper.selectSeveral(limit, offset);
    }

    public void update(String id, String name, int age) throws Exception {
        User obj = new User();
        obj.setId(Long.parseLong(id));
        obj.setName(name);
        obj.setAge(age);
        userMapper.update(obj);
    }

    public void delete(List<String> ids) throws Exception {
        userMapper.delete(ids);
    }
}
